package com.tinysand.advert.service;

import com.alibaba.fastjson.JSON;
import com.tinysand.advert.Application;
import com.tinysand.advert.constant.CommonStatus;
import com.tinysand.advert.constant.DataConstant;
import com.tinysand.advert.entity.AdvertPlan;
import com.tinysand.advert.entity.AdvertUnit;
import com.tinysand.advert.entity.Advertisement;
import com.tinysand.advert.entity.condition.AdUnitDistrict;
import com.tinysand.advert.entity.condition.AdUnitInterest;
import com.tinysand.advert.entity.condition.AdUnitKeyWord;
import com.tinysand.advert.entity.condition.AdvertUnitRelation;
import com.tinysand.advert.repository.*;
import com.tinysand.advert.support.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created By TINY
 * Create Time 2020/2/27
 **/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class},
        webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class DumpDataService {

    @Autowired
    private PlanRepository planRepository;

    @Autowired
    private UnitRepository unitRepository;

    @Autowired
    private AdvertRepository advertRepository;

    @Autowired
    private AdUnitRelRepository adUnitRelRepository;

    @Autowired
    private InterestRepository interestRepository;

    @Autowired
    private DistrictRepository districtRepository;

    @Autowired
    private KeywordRepository keywordRepository;

    @Test
    public void dumpAdTableData() throws IOException {

        if (!Files.exists(Paths.get(DataConstant.DATA_ROOT_DIR))) {
            Files.createDirectory(Paths.get(DataConstant.DATA_ROOT_DIR));
        }

        dumpAdPlanTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_PLAN)
        );

        dumpAdUnitTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT)
        );

        dumpAdvertTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_ADVERT)
        );

        dumpAdUnitRelTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_REL)
        );

        dumpUnitDistrictTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_DISTRICT)
        );

        dumpUnitInterestTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_INTEREST)
        );

        dumpUnitKeywordTable(String.format("%s%s",
                DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_KEYWORD)
        );
    }

    private void dumpAdPlanTable(String fileName) {
        List<AdvertPlan> advertPlans = planRepository
                .findAllByPlanStatus(CommonStatus.VALID.getStatus());
        if (CollectionUtils.isEmpty(advertPlans)) {
            System.err.println("推广计划为空");
            return;
        }

        List<AdPlanTable> planTables = new ArrayList<>();
        advertPlans.forEach(p -> planTables.add(
                new AdPlanTable(
                        p.getId(),
                        p.getUserId(),
                        p.getPlanStatus(),
                        p.getStartDate(),
                        p.getEndDate()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdPlanTable planTable : planTables) {
                writer.write(JSON.toJSONString(planTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpAdUnitTable(String fileName) {
        List<AdvertUnit> advertUnits = unitRepository
                .findAllByUnitStatus(CommonStatus.VALID.getStatus());
        if (CollectionUtils.isEmpty(advertUnits)) {
            return;
        }

        List<AdUnitTable> unitTables = new ArrayList<>();
        advertUnits.forEach(u -> unitTables.add(
                new AdUnitTable(
                        u.getId(),
                        u.getPlanId(),
                        u.getUnitStatus(),
                        u.getPositionType()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitTable unitTable : unitTables) {
                writer.write(JSON.toJSONString(unitTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpAdvertTable(String fileName) {
        List<Advertisement> advertisements = advertRepository.findAll();
        if (CollectionUtils.isEmpty(advertisements)) {
            return;
        }

        List<AdvertTable> advertTables = new ArrayList<>();
        advertisements.forEach(a -> advertTables.add(
                new AdvertTable(
                        a.getId(),
                        a.getName(),
                        a.getType(),
                        a.getMaterialType(),
                        a.getHeight(),
                        a.getWidth(),
                        a.getAuditStatus(),
                        a.getUrl()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdvertTable advertTable : advertTables) {
                writer.write(JSON.toJSONString(advertTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpAdUnitRelTable(String fileName) {
        List<AdvertUnitRelation> adUnitRelList = adUnitRelRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitRelList)) {
            return;
        }

        List<AdUnitRelTable> adUnitRelTables = new ArrayList<>();
        adUnitRelList.forEach(a -> adUnitRelTables.add(
                new AdUnitRelTable(
                        a.getCreativeId(),
                        a.getUnitId()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitRelTable adUnitRelTable : adUnitRelTables) {
                writer.write(JSON.toJSONString(adUnitRelTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpUnitDistrictTable(String fileName) {
        List<AdUnitDistrict> adUnitDistricts = districtRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitDistricts)) {
            return;
        }

        List<DistrictTable> districtTables = new ArrayList<>();
        adUnitDistricts.forEach(d -> districtTables.add(
                new DistrictTable(
                        d.getUnitId(),
                        d.getProvince(),
                        d.getCity()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (DistrictTable districtTable : districtTables) {
                writer.write(JSON.toJSONString(districtTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpUnitInterestTable(String fileName) {
        List<AdUnitInterest> adUnitInterests = interestRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitInterests)) {
            return;
        }

        List<InterestTable> interestTables = new ArrayList<>();
        adUnitInterests.forEach(i -> interestTables.add(
                new InterestTable(
                        i.getUnitId(),
                        i.getItTag()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (InterestTable interestTable : interestTables) {
                writer.write(JSON.toJSONString(interestTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }

    private void dumpUnitKeywordTable(String fileName) {
        List<AdUnitKeyWord> adUnitKeyWords = keywordRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitKeyWords)) {
            return;
        }

        List<KeywordTable> keywordTables = new ArrayList<>();
        adUnitKeyWords.forEach(i -> keywordTables.add(
                new KeywordTable(
                        i.getUnitId(),
                        i.getKeyword()
                )
        ));

        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (KeywordTable keywordTable: keywordTables) {
                writer.write(JSON.toJSONString(keywordTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("数据导出失败");
        }
    }
}
